// repositories/order.go
package repositories

import (
	"fmt"
	"myapi/models"
	"time"

	"gorm.io/gorm"
)

// OrderRepository 处理订单数据库操作
type OrderRepository struct{}

// Create 创建新订单
func (r *OrderRepository) Create(order *models.Order) error {
	return DB.Transaction(func(tx *gorm.DB) error {
		// 生成订单号
		if order.OrderNo == "" {
			order.OrderNo = r.generateOrderNo()
		}

		// 计算订单项金额
		for i := range order.Items {
			order.Items[i].CalculateAmount()
		}

		// 计算订单总金额
		order.CalculateTotalAmount()

		// 创建订单和订单项
		if err := tx.Create(order).Error; err != nil {
			return err
		}

		return nil
	})
}

// FindByID 通过ID查找订单（包含关联数据）
func (r *OrderRepository) FindByID(id uint) (*models.Order, error) {
	var order models.Order
	err := DB.Preload("Customer").Preload("Creator").Preload("Items").First(&order, id).Error
	if err != nil {
		return nil, err
	}
	return &order, nil
}

// FindByOrderNo 通过订单号查找订单
func (r *OrderRepository) FindByOrderNo(orderNo string) (*models.Order, error) {
	var order models.Order
	err := DB.Preload("Customer").Preload("Creator").Preload("Items").Where("order_no = ?", orderNo).First(&order).Error
	if err != nil {
		return nil, err
	}
	return &order, nil
}

// FindAll 获取所有订单（分页）
func (r *OrderRepository) FindAll(page, pageSize int) ([]models.Order, int64, error) {
	var orders []models.Order
	var count int64

	offset := (page - 1) * pageSize

	// 获取总数
	if err := DB.Model(&models.Order{}).Count(&count).Error; err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	if err := DB.Preload("Customer").Preload("Creator").Preload("Items").
		Offset(offset).Limit(pageSize).Find(&orders).Error; err != nil {
		return nil, 0, err
	}

	return orders, count, nil
}

// FindByCustomerID 根据客户ID查找订单
func (r *OrderRepository) FindByCustomerID(customerID uint, page, pageSize int) ([]models.Order, int64, error) {
	var orders []models.Order
	var count int64

	offset := (page - 1) * pageSize

	// 获取总数
	if err := DB.Model(&models.Order{}).Where("customer_id = ?", customerID).Count(&count).Error; err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	if err := DB.Preload("Customer").Preload("Creator").Preload("Items").
		Where("customer_id = ?", customerID).
		Offset(offset).Limit(pageSize).Find(&orders).Error; err != nil {
		return nil, 0, err
	}

	return orders, count, nil
}

// FindByStatus 根据状态查找订单
func (r *OrderRepository) FindByStatus(status models.OrderStatus, page, pageSize int) ([]models.Order, int64, error) {
	var orders []models.Order
	var count int64

	offset := (page - 1) * pageSize

	// 获取总数
	if err := DB.Model(&models.Order{}).Where("status = ?", status).Count(&count).Error; err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	if err := DB.Preload("Customer").Preload("Creator").Preload("Items").
		Where("status = ?", status).
		Offset(offset).Limit(pageSize).Find(&orders).Error; err != nil {
		return nil, 0, err
	}

	return orders, count, nil
}

// Update 更新订单信息
func (r *OrderRepository) Update(order *models.Order) error {
	return DB.Transaction(func(tx *gorm.DB) error {
		// 重新计算订单项金额
		for i := range order.Items {
			order.Items[i].CalculateAmount()
		}

		// 重新计算订单总金额
		order.CalculateTotalAmount()

		// 更新订单
		if err := tx.Save(order).Error; err != nil {
			return err
		}

		return nil
	})
}

// UpdateStatus 更新订单状态
func (r *OrderRepository) UpdateStatus(id uint, status models.OrderStatus) error {
	return DB.Model(&models.Order{}).Where("id = ?", id).Update("status", status).Error
}

// Delete 删除订单
func (r *OrderRepository) Delete(id uint) error {
	return DB.Transaction(func(tx *gorm.DB) error {
		// 删除订单项
		if err := tx.Where("order_id = ?", id).Delete(&models.OrderItem{}).Error; err != nil {
			return err
		}

		// 删除订单
		if err := tx.Delete(&models.Order{}, id).Error; err != nil {
			return err
		}

		return nil
	})
}

// generateOrderNo 生成订单号
func (r *OrderRepository) generateOrderNo() string {
	now := time.Now()
	// 格式：WHS + 年月日 + 10位随机数
	return fmt.Sprintf("WHS%s%010d", now.Format("20060102"), now.UnixNano()%10000000000)
}

// GetOrderStatistics 获取订单统计信息
func (r *OrderRepository) GetOrderStatistics() (map[string]interface{}, error) {
	var stats map[string]interface{} = make(map[string]interface{})

	// 总订单数
	var totalCount int64
	if err := DB.Model(&models.Order{}).Count(&totalCount).Error; err != nil {
		return nil, err
	}
	stats["total_orders"] = totalCount

	// 各状态订单数
	var statusCounts []struct {
		Status string `json:"status"`
		Count  int64  `json:"count"`
	}
	if err := DB.Model(&models.Order{}).
		Select("status, count(*) as count").
		Group("status").
		Scan(&statusCounts).Error; err != nil {
		return nil, err
	}
	stats["status_counts"] = statusCounts

	// 今日订单数
	today := time.Now().Format("2006-01-02")
	var todayCount int64
	if err := DB.Model(&models.Order{}).
		Where("DATE(created_at) = ?", today).
		Count(&todayCount).Error; err != nil {
		return nil, err
	}
	stats["today_orders"] = todayCount

	// 总销售额
	var totalAmount float64
	if err := DB.Model(&models.Order{}).
		Select("COALESCE(SUM(total_amount), 0)").
		Where("status != ?", models.OrderStatusCancelled).
		Scan(&totalAmount).Error; err != nil {
		return nil, err
	}
	stats["total_amount"] = totalAmount

	return stats, nil
}
